package com.dog.basics.service.common.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.Validator;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dog.basics.bean.dto.admin.common.BannerAddDto;
import com.dog.basics.bean.dto.admin.common.BannerEditDto;
import com.dog.basics.bean.dto.admin.common.BannerFromDto;
import com.dog.basics.bean.model.common.SysBanner;
import com.dog.basics.bean.model.common.SysBannerGenus;
import com.dog.basics.bean.vo.admin.common.BannerVo;
import com.dog.basics.common.util.Json;
import com.dog.basics.common.util.PageParam;
import com.dog.basics.dao.common.SysBannerGenusMapper;
import com.dog.basics.dao.common.SysBannerMapper;
import com.dog.basics.security.util.SecurityUtils;
import com.dog.basics.service.common.ISysBannerService;
import lombok.AllArgsConstructor;
import ma.glasnost.orika.MapperFacade;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 轮播图 服务实现类
 * </p>
 *
 * @author fengjukang
 * @since 2019-12-13
 */
@Service
@AllArgsConstructor
public class SysBannerServiceImpl extends ServiceImpl<SysBannerMapper, SysBanner> implements ISysBannerService {
    private final SysBannerGenusMapper sysBannerGenusMapper;
    private final MapperFacade mapperFacade;

    /**
     * 分页的条件公用类
     *
     * @param name
     * @param enusIds
     */
    public List<Long> getuserIdsWhere(String name, List<Long> enusIds) {
        List<Long> collect = sysBannerGenusMapper.selectList(Wrappers.<SysBannerGenus>lambdaQuery().like(StrUtil.isNotBlank(name), SysBannerGenus::getName, name)).stream().map(e -> e.getId()).collect(Collectors.toList());
        if (CollUtil.isNotEmpty(collect)) {
            enusIds = collect;
        } else {
            enusIds.add(-2L);
        }
        return enusIds;
    }

    /**
     * @Description: 分页轮播图列表
     * @Param: BannerFromDto
     * @return: IPage<BannerVo>
     * @Author: wph
     * @Date:
     */
    @Override
    public IPage<BannerVo> getPageList(PageParam page, BannerFromDto obj) {
        // 判断genusIds
        List<Long> enusIds = CollUtil.newArrayList();
        if (StrUtil.isNotBlank(obj.getGenusName())) {
            enusIds = getuserIdsWhere(obj.getGenusName(), enusIds);
        }
        IPage iPage = this.page(page, new LambdaQueryWrapper<SysBanner>()
                .in(CollUtil.isNotEmpty(enusIds), SysBanner::getGenusId, enusIds)
                .like(StrUtil.isNotBlank(obj.getTitle()), SysBanner::getTitle, obj.getTitle())
                .orderBy(Boolean.TRUE, obj.getIsOrderByAvg(), SysBanner::getCreateTime));
        List<SysBanner> records = iPage.getRecords();
        iPage.setRecords(records.stream().map(e -> {
            BannerVo bannerVo = new BannerVo();
            BeanUtil.copyProperties(e, bannerVo);
            SysBannerGenus sysBannerGenus = sysBannerGenusMapper.selectById(e.getGenusId());
            bannerVo.setGenusName(ObjectUtil.isNotNull(sysBannerGenus) ? sysBannerGenus.getName() : "");
            List<String> ts = null;
            try {
                ts = Json.parseArray(e.getImgId(), String[].class);
            } catch (Exception ex) {
                ts = CollUtil.newArrayList();
            }
            bannerVo.setImgId(ts);

            return bannerVo;
        }).collect(Collectors.toList()));
        return iPage;
    }

    /**
     * @Description: APi轮播图
     * @Param: code
     * @return: BannerVo
     * @Author: wph
     * @Date:
     */
    @Override
    public List<BannerVo> getApiBannerVoInfo(String code) {
        List<Long> genusIds = sysBannerGenusMapper.selectList(Wrappers.<SysBannerGenus>lambdaQuery().eq(SysBannerGenus::getCode, code)).stream().map(e -> e.getId()).collect(Collectors.toList());
        if (CollUtil.isEmpty(genusIds)) {
            genusIds.add(-2L);
        }
        List<SysBanner> list = this.list(new LambdaQueryWrapper<SysBanner>().in(SysBanner::getGenusId, genusIds).orderByDesc(SysBanner::getCreateTime));
        Validator.validateTrue(CollUtil.isNotEmpty(list), "所属广告为空!");
        List<BannerVo> newList = list.stream().map(e -> {
            BannerVo bannerVo = new BannerVo();
            BeanUtil.copyProperties(e, bannerVo);
            SysBannerGenus sysBannerGenus = sysBannerGenusMapper.selectById(e.getGenusId());
            bannerVo.setGenusName(ObjectUtil.isNotNull(sysBannerGenus) ? sysBannerGenus.getName() : "");
            List<String> ts = null;
            try {
                ts = Json.parseArray(e.getImgId(), String[].class);
            } catch (Exception ex) {
                ts = CollUtil.newArrayList();
            }
            bannerVo.setImgId(ts);
            return bannerVo;
        }).collect(Collectors.toList());

        return newList;
    }

    /**
     * @Description: 增加轮播图
     * @Param: BannerAddDto
     * @return: Boolean
     * @Author: wph
     * @Date: 2020/05/29  0027
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean saveObj(BannerAddDto bannerAddDto) {
        SysBannerGenus sysBannerGenus = sysBannerGenusMapper.selectById(bannerAddDto.getGenusId());
        Validator.validateNotNull(sysBannerGenus, "广告所属地不存在!");
        SysBanner dogBanner = new SysBanner();
        BeanUtil.copyProperties(bannerAddDto, dogBanner);
        dogBanner.setImgId(JSONUtil.toJsonStr(bannerAddDto.getImgId()));
        dogBanner.setCreateTime(DateUtil.currentSeconds());
        dogBanner.setCreateBy(SecurityUtils.getSysUser().getUserId());
        return this.save(dogBanner);
    }

    /**
     * @Description: 修改轮播图
     * @Param: BannerEditDto
     * @return: Boolean
     * @Author: wph
     * @Date: 2020/05/29  0027
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean editObj(BannerEditDto bannerEditDto) {
        SysBanner dogBanner = this.getById(bannerEditDto.getId());
        Validator.validateNotNull(dogBanner, "无此数据");
        SysBannerGenus sysBannerGenus = sysBannerGenusMapper.selectById(bannerEditDto.getGenusId());
        Validator.validateNotNull(sysBannerGenus, "广告所属地不存在!");

        BeanUtil.copyProperties(bannerEditDto, dogBanner);
        dogBanner.setImgId(JSONUtil.toJsonStr(bannerEditDto.getImgId()));
        dogBanner.setUpdateTime(DateUtil.currentSeconds());
        dogBanner.setUpdateBy(SecurityUtils.getSysUser().getUserId());
        return this.updateById(dogBanner);
    }

    /**
     * @Description: 删除轮播图
     * @Param: ids
     * @return: Boolean
     * @Author: wph
     * @Date: 2020/05/29  0027
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean deleteObj(List<Long> ids) {
        // 判断是否为空
        Validator.validateTrue(CollUtil.isNotEmpty(ids), "主键标识为空");
        return this.removeByIds(ids);
    }

}
